//
//  AddItemViewController.swift
//  Todo-List
//
//  Created by jiangdan on 2019/9/23.
//  Copyright © 2019年 stu. All rights reserved.
//

import UIKit

protocol AddItemViewControllerDelegate:class {
    func AddItemViewController(_ controller:AddItemViewController,endAdding item:TodoItem)
    func AddItemViewController(_ controller:AddItemViewController,endEditing item:TodoItem)
}

class AddItemViewController: UITableViewController,UITextFieldDelegate {
    weak var delegate:AddItemViewControllerDelegate?
    
    var itemToEdit:TodoItem?
    var dueDate = Date()
    var datePickerVisible = false
    
    func showDatePicker() {
            datePickerVisible = true
        let indexP
    }
    

    @IBOutlet weak var dueDateLable: UILabel!
    @IBOutlet weak var remindSwitch: UISwitch!
    @IBOutlet weak var inputTextFiled: UITextField!
    @IBOutlet weak var doneBarButton: UIBarButtonItem!
    
    @IBAction func cancel(_ sender: Any) {
        dismiss(animated: true, completion: nil)
    }
    @IBAction func commit(_ sender: Any) {
        if let item = itemToEdit {
            item.text = inputTextFiled.text!
            item.shouldRemind = remindSwitch.isOn
            item.dueDate = dueDate
            delegate?.AddItemViewController(self, endAdding: item )
        }else {
        let item = TodoItem()
            item.text = inputTextFiled.text!
            item.checked = false
            item.shouldRemind = remindSwitch.isOn
            item.dueDate = dueDate
        delegate?.AddItemViewController(self, endAdding: item )
        }
        dismiss(animated: true, completion: nil)
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        if let item = itemToEdit {
            title = "编辑备忘录"
            inputTextFiled.text = item.text
            remindSwitch.isOn = item.shouldRemind
            dueDate = item.dueDate
        }else {
            title = "新建备忘录"
        }
        updateDueDateLable()
    }
    func updateDueDateLable() {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy年mm月dd日 HH:mm"
        dueDateLable.text = formatter.string(from:dueDate)
    }
    
    

    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        inputTextFiled.becomeFirstResponder()
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let oldStr = textField.text! as NSString
        let newStr = oldStr.replacingCharacters(in: range, with: string)
        
        doneBarButton.isEnabled = newStr.count > 0
        
        return true
    }
    
}
